﻿using System;
using System.Linq;
using System.Web;
using System.Web.Routing;
using EasySite.Infrastructure.Extensions;

namespace EasySite.Web.Mvc
{
    public class DefinedControllerConstraint : IRouteConstraint
    {
        #region Implementation of IRouteConstraint

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (routeDirection != RouteDirection.IncomingRequest)
            {
                return true;
            }
            var controller = values["controller"] + "controller";
            foreach (var controllerType in EasySiteContext.Current.DefinedControllerCache.ControllerTypes)
            {
                if (controller.Eq(controllerType.Name))
                {
                    var action = values["action"] != null ? values["action"].ToString() : string.Empty;
                    return controllerType.Methods.Any(m => m.Eq(action));
                }
            }
            return false;
        }

        #endregion
    }

}